import datetime
from fastapi import FastAPI
from fastapi.concurrency import asynccontextmanager
from app.dependencies.database import db


@asynccontextmanager
async def lifespan(app: FastAPI):
    '''生命周期'''
    # 启用数据库
    await db.connect()
    print("Database connected.", datetime.datetime.now())
    # 同步路由到数据
    yield
    await db.disconnect()
    print("Database disconnected.", datetime.datetime.now())


def configure_routes(app: FastAPI):
    # from app.dependencies.verify import admin_verify_token
    from app.api.h5.controller.shop.shop import shop
    from app.api.h5.controller.coupon.coupon import coupon
    from app.api.h5.controller.order.order import order
    # admin_verify_token_depend = [Depends(admin_verify_token)]
    h5_prefix = "/api/h5"

    app.include_router(shop, prefix=h5_prefix)
    app.include_router(coupon, prefix=h5_prefix)
    app.include_router(order, prefix=h5_prefix)


def configure_middleware(app: FastAPI):
    """配置中间件"""
    # from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware
    from app.middlewares.cors import init_cors_middleware
    from app.middlewares.time_out import init_timeout_middleware
    # app.add_middleware(ProxyHeadersMiddleware)
    init_cors_middleware(app)
    init_timeout_middleware(app)


def create_h5():
    app = FastAPI(lifespan=lifespan)

    # 中间件
    configure_middleware(app)

    # 全局异常
    from app.exceptions.handler import configure_exception
    configure_exception(app)

    # 路由
    configure_routes(app)
    return app
